package com.android.jay.lib_audio.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.transition.TransitionInflater;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.jay.lib_audio.R;
import com.android.jay.lib_audio.api.RequestCenter;
import com.android.jay.lib_audio.app.AudioHelper;
import com.android.jay.lib_audio.mediaplayer.core.AudioController;
import com.android.jay.lib_audio.mediaplayer.core.CustomMediaPlayer;
import com.android.jay.lib_audio.mediaplayer.db.GreenDaoHelper;
import com.android.jay.lib_audio.mediaplayer.event.AudioCompletion;
import com.android.jay.lib_audio.mediaplayer.event.AudioFavouriteEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioLoadEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioPauseEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioPlayModeEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioProgressEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioStartEvent;
import com.android.jay.lib_audio.mediaplayer.model.AudioBean;
import com.android.jay.lib_audio.mediaplayer.utils.Utils;
import com.android.jay.lib_commin_ui.base.BaseActivity;
import com.android.jay.lib_image_loader.app.ImageLoaderManager;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataListener;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDownloadListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;

/**
 * Created by wzp on 2020/1/15 0015.
 * <p>
 * 描述  ：音乐界面
 */
public class MusicPlayerActivity extends BaseActivity {

    private RelativeLayout mBgView;
    private TextView mInfoView;
    private TextView mAuthorView;
    private ImageView mFavouriteView;

    private SeekBar mProgressVies;
    private TextView mStartTimeView;
    private TextView mTotalTimeView;

    private ImageView mPlayModeView;
    private ImageView mPlayView;
    private ImageView mNextView;
    private ImageView mPreViousView;
    private Animator animator;


    /**
     * data
     **/
    private AudioBean mAudioBean;
    private AudioController.PlayMode mPlayMode;
    private ImageView mDownLoad;
//    //当前播放歌曲的总时间
//    private int totalTime;
//    //当前播放歌曲的播放时间
//    private int currentTime;


    public static void start(Activity context) {
        Intent intent = new Intent(context, MusicPlayerActivity.class);
        ActivityCompat.startActivity(context, intent,
                ActivityOptionsCompat.makeSceneTransitionAnimation(context).toBundle());
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setEnterTransition(
                    TransitionInflater.from(this)
                            .inflateTransition(R.transition.transition_bottom2top)
            );
        }
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_music_service_layout);
        initData();
        initView();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        mDownLoad = findViewById(R.id.download);
        mDownLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("download", "download=" + mAudioBean.mUrl);
                RequestCenter.getDownLoadRequest("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559698076304&di=e6e99aa943b72ef57b97f0be3e0d2446&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201401%2F04%2F20140104170315_XdG38.jpeg", new DisposeDownloadListener() {
                    @Override
                    public void onProgress(int progress) {
                        Log.e("download", progress + "");

                    }

                    @Override
                    public void onSuccess(Object responseObj) {
                        Log.e("download", responseObj.toString() + "");
                    }

                    @Override
                    public void onFailure(Object reasonObj) {
                        Log.e("download", reasonObj.toString() + "");
                    }
                });
            }
        });
        mBgView = findViewById(R.id.root_layout);
        ImageLoaderManager.getInstance()
                .displayImageForViewGroup(mBgView, mAudioBean.albumPic, true);
        //退出按钮
        findViewById(R.id.back_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //标题
        findViewById(R.id.title_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //分享
        findViewById(R.id.share_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareMusic(mAudioBean.mUrl, mAudioBean.name);
            }
        });
        //歌单
        findViewById(R.id.show_list_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mInfoView = findViewById(R.id.album_view);
        mInfoView.setText(mAudioBean.albumInfo);
        mInfoView.requestFocus();//跑马灯焦点获取

        mAuthorView = findViewById(R.id.author_view);
        mAuthorView.setText(mAudioBean.author);

        mFavouriteView = findViewById(R.id.favourite_view);
        mFavouriteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否收藏
                //数据库查询 是否收藏并发送事件出去
                AudioController.getInstance().changeFavouriteState();
            }
        });

        changeFavouriteStatus(false);

        /**
         * 进度相关
         * **/
        mStartTimeView = findViewById(R.id.start_time_view);
        mTotalTimeView = findViewById(R.id.total_time_view);
        mProgressVies = findViewById(R.id.progress_view);
        mProgressVies.setProgress(0);
//        mProgressVies.setEnabled(false);


        //滑动控制监听
        mProgressVies.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.e("wwwww", "progress===" + progress);
//                AudioController.getInstance().setMusicePostion(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//               int current = totalTime  seekBar.getProgress();
                AudioController.getInstance().setMusicePostion(seekBar.getProgress());

            }
        });


        //播放模式
        mPlayModeView = findViewById(R.id.play_mode_view);
        mPlayModeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (mPlayMode) {
                    case LOOP:
                        AudioController.getInstance()
                                .setPlayMode(AudioController.PlayMode.RANDOM);
                        break;
                    case RANDOM:
                        AudioController.getInstance()
                                .setPlayMode(AudioController.PlayMode.REPEAT);
                        break;
                    case REPEAT:
                        AudioController.getInstance()
                                .setPlayMode(AudioController.PlayMode.LOOP);
                        break;
                }

            }
        });
        //更新播放模式
        updatePlayModeView();
        mPreViousView = findViewById(R.id.previous_view);
        mPreViousView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一首

                AudioController.getInstance().previous();
            }
        });

        mNextView = findViewById(R.id.next_view);
        mNextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 下一首
                AudioController.getInstance().next();
            }
        });

        mPlayView = findViewById(R.id.play_view);
        mPlayView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioController.getInstance().playOrPause();

            }
        });


    }

    private void updatePlayModeView() {
        switch (mPlayMode) {
            case REPEAT:
                mPlayModeView.setImageResource(R.mipmap.player_once);
                break;
            case RANDOM:
                mPlayModeView.setImageResource(R.mipmap.player_random);
                break;
            case LOOP:
                mPlayModeView.setImageResource(R.mipmap.player_loop);
                break;
        }

    }


    //是否执行收藏动画
    private void changeFavouriteStatus(boolean anim) {
        if (GreenDaoHelper.selectFavourite(mAudioBean) != null) {
            mFavouriteView.setImageResource(R.mipmap.audio_aeh);
        } else {
            mFavouriteView.setImageResource(R.mipmap.audio_aef);
        }
        //是否需要启动动画
        if (anim) {
            // 完成收藏效果动画
            if (animator != null) {
                animator.end();
            }
            PropertyValuesHolder animX =
                    PropertyValuesHolder.ofFloat(View.SCALE_X.getName()
                            , 1.0f, 1.2f, 1.0f);
            PropertyValuesHolder animY =
                    PropertyValuesHolder.ofFloat(View.SCALE_Y.getName()
                            , 1.0f, 1.2f, 1.0f);
            animator = ObjectAnimator.ofPropertyValuesHolder(animX, animY);
            //差时器
            animator.setInterpolator(new AccelerateDecelerateInterpolator());
            animator.setDuration(300);
            animator.start();
        }
    }


    private void shareMusic(String mUrl, String name) {

    }

    private void initData() {
        mAudioBean = AudioController.getInstance().getNowPlaying();
        mPlayMode = AudioController.getInstance().getPlayMode();
    }


    /**
     * 加载
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioLoadEvent(AudioLoadEvent event) {
        mAudioBean = event.mAudioBean;
        showLoadingView();

    }

    private void showLoadingView() {
        ImageLoaderManager.getInstance()
                .displayImageForViewGroup(mBgView, mAudioBean.albumPic, true);
        mInfoView.setText(mAudioBean.albumInfo);
        mAuthorView.setText(mAudioBean.author);
        changeFavouriteStatus(false);
        mProgressVies.setProgress(0);
    }

    /***
     * 开始
     * **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioStartEvent(AudioStartEvent event) {
        showPlayView();
    }

    private void showPlayView() {
        mPlayView.setImageResource(R.mipmap.audio_aj6);
    }

    /**
     * 暂停
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioPauseEvent(AudioPauseEvent event) {
        showPauseView();
    }

    private void showPauseView() {
        mPlayView.setImageResource(R.mipmap.audio_aj7);
    }


    /**
     * 收藏
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioFavouriteEvent(AudioFavouriteEvent event) {
        changeFavouriteStatus(true);
    }

    /**
     * 切换模式
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioPlayModeEvent(AudioPlayModeEvent event) {
        mPlayMode = event.playMode;
        updatePlayModeView();
    }

    /**
     * 进度条
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioProgressChangeEvent(AudioProgressEvent event) {
        int totalTime = event.mTotalTime;
        int currentTime = event.mCurrentTime;
        mTotalTimeView.setText(Utils.formatTime(totalTime));
        mStartTimeView.setText(Utils.formatTime(currentTime));
        mProgressVies.setMax(totalTime);
        mProgressVies.setProgress(currentTime);
        if (event.mStatus == CustomMediaPlayer.Status.PAUSE) {
            showPauseView();
        } else {
            showPlayView();
        }
    }

    /**
     * 歌曲播放完毕
     **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioCompleteEvent(AudioCompletion event) {

        AudioController.getInstance().next();
    }


}
